package com.zy.tree;

import java.util.ArrayList;
import java.util.List;

public class TreeUtil {

  private List<TreeNode> treeNodeList =new ArrayList<>();

  public TreeUtil(List<TreeNode> list){
    treeNodeList = list;
  }

  /**
   * 获取节点信息
   * @param nodeId 节点ID
   * @return
   */
  public TreeNode getNodeById(int nodeId){
    TreeNode treeNode = new TreeNode();
    for (TreeNode item : treeNodeList) {
      if (item.getId() == nodeId) {
        treeNode = item;
        break;
      }
    }
    return treeNode;
  }

  /**
   * 获取子节点信息
   * @param nodeId 节点ID
   * @return
   */
  public List<TreeNode> getChildrenNodeById(int nodeId){
    List<TreeNode> childrenTreeNode = new ArrayList<TreeNode>();
    for (TreeNode item : treeNodeList) {
      if(item.getParentId() == nodeId){
        childrenTreeNode.add(item);
      }
    }
    return childrenTreeNode;
  }

  /**
   * 递归生成Tree结构数据
   * @param rootId 根节点ID
   * @return
   */
  public TreeNode generateTreeNode(int rootId){
    TreeNode root = this.getNodeById(rootId);
    List<TreeNode> childrenTreeNode = this.getChildrenNodeById(rootId);
    for (TreeNode item : childrenTreeNode) {
      TreeNode node = this.generateTreeNode(item.getId());
      root.getChildrenList().add(node);
    }
    return root;
  }

  public static void main(String[] args) {
    List<TreeNode> nodeList = new ArrayList<>();
    TreeNode treeNode = new TreeNode();
    treeNode.setId(1);
    treeNode.setName("中国");
    treeNode.setParentId(0);
    nodeList.add(treeNode);
    treeNode = new TreeNode();
    treeNode.setId(2);
    treeNode.setName("北京市");
    treeNode.setParentId(1);
    nodeList.add(treeNode);
    treeNode = new TreeNode();
    treeNode.setId(3);
    treeNode.setName("浙江省");
    treeNode.setParentId(1);
    nodeList.add(treeNode);
    treeNode = new TreeNode();
    treeNode.setId(4);
    treeNode.setName("杭州市");
    treeNode.setParentId(3);
    nodeList.add(treeNode);
    treeNode = new TreeNode();
    treeNode.setId(5);
    treeNode.setName("西湖区");
    treeNode.setParentId(4);
    nodeList.add(treeNode);
    treeNode = new TreeNode();
    treeNode.setId(6);
    treeNode.setName("滨江区");
    treeNode.setParentId(4);
    nodeList.add(treeNode);
    treeNode = new TreeNode();
    treeNode.setId(7);
    treeNode.setName("金华市");
    treeNode.setParentId(3);
    nodeList.add(treeNode);
    TreeUtil treeUtil = new TreeUtil(nodeList);
    treeNode = treeUtil.generateTreeNode(1);
    System.out.println("树状结构Json格式数据：" + JsonUtils.objectToJson(treeNode, 1));
  }
}